package com.zhaolang.qogir.ui.processed;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.suke.widget.SwitchButton;
import com.umeng.socialize.utils.Log;
import com.zhaolang.qogir.R;
import com.zhaolang.qogir.bean.OrderBean;
import com.zhaolang.qogir.bean.OrderMenu;
import com.zhaolang.qogir.bean.ProcessedOrderInfo;
import com.zhaolang.qogir.bean.TicketBean;
import com.zhaolang.qogir.domain.BaseCall;
import com.zhaolang.qogir.domain.OrderManage;
import com.zhaolang.qogir.domain.ReqFactory;
import com.zhaolang.qogir.ui.BaseFragment;
import com.zhaolang.qogir.ui.adapter.FragmentProcessedNewAdapter;
import com.zhaolang.qogir.util.HttpConstant;
import com.zhaolang.qogir.util.PrintUtil;
import com.zhaolang.qogir.util.Slog;
import com.zhaolang.qogir.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.taobao.accs.client.AccsConfig.build;

public class FragmentProcessedNew extends BaseFragment implements PullToRefreshBase.OnRefreshListener2<ListView>,
        SwitchButton.OnCheckedChangeListener {
    private PullToRefreshListView pullListView;
    private ListView listView;
    private SwitchButton btn_printer_setting;
    private View header_view;
    private FragmentProcessedNewAdapter fragmentProcessedNewAdapter;
    private OrderManage orderManage;
    SoundPool sp; // 声明SoundPool的引用
    HashMap<Integer, Integer> hm; // 声明一个HashMap来存放声音文件
    int currStreamId;// 当前正播放的streamId

    private static final int BASE = 0x200;
    private static final int MSG_FRESH_ORDER_UI = BASE + 1;
    private static final int MSG_REFRESH_ORDER_UI = BASE + 2;
    private static final int MSG_REFRESH_TOAST = BASE + 3;
    private static final int MSG_TIMER_CLOCK = BASE + 4;
    private OkHttpClient okHttpClient = new OkHttpClient();
    private Timer timer;
    private static final int TIMER_CLOCK = 3000;

    private BaseCall<OrderManage.OrderReq> mOrderCallback = new BaseCall<OrderManage.OrderReq>() {
        @Override
        public void call(OrderManage.OrderReq resp) {
            // TODO Auto-generated method stub
            if (resp.isRequestSuccess()) {
                List<OrderBean> listBean = resp.getOrderBean();
                handler.sendMessage(Message.obtain(handler, MSG_FRESH_ORDER_UI, listBean));
            } else {
                Slog.e("Failed update mOrderCallback!!!!!!!  " + resp.getMessage());
            }
        }
    };

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_FRESH_ORDER_UI:
                    List<OrderBean> listBean = (List<OrderBean>) msg.obj;
                    if (listBean.size() == 0) {
                        ToastUtils.showShort(getContext(), getString(R.string.err_no_new_order));
                    } else if (listBean.size() > 0) {
                        playSound(1, 0);
                    }
                    setValidateData(listBean);
                    fragmentProcessedNewAdapter.setData(setValidateData(listBean));
                    fragmentProcessedNewAdapter.notifyDataSetChanged();
                    printTicket(listBean);
                    break;
                case MSG_REFRESH_ORDER_UI:
                    orderManage.readAllOrderAsync(mOrderCallback);
                    break;
                case MSG_REFRESH_TOAST:
                    ToastUtils.showShort(getContext(), getString(R.string.err_no_printer));
                    break;
                case MSG_TIMER_CLOCK:
                    pullListView.setRefreshing();
                    activateTimerSchedule();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setContentView(R.layout.fragment_processed_new);
        orderManage = ReqFactory.buildInterface(getActivity(),
                OrderManage.class);
        initSoundPool();
        initView();

        okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();

        return getContentView();
    }

    private List<ProcessedOrderInfo> setValidateData() {
        List<ProcessedOrderInfo> list = new ArrayList<>();
//        ProcessedOrderInfo processedOrderInfo = new ProcessedOrderInfo();
//        processedOrderInfo.setDeliveryStatus(getContext().getResources().getString(R.string.ui_processed_fast_delivery));
//        processedOrderInfo.setLastComment(getContext().getResources().getString(R.string.ui_processed_last_comment));
//        processedOrderInfo.setUserName(getContext().getResources().getString(R.string.ui_processed_name));
//        processedOrderInfo.setUserAddress(getContext().getResources().getString(R.string.ui_processed_user_address));
//        processedOrderInfo.setOrderProductName(getContext().getResources().getString(R.string.ui_shop_product_name));
//        processedOrderInfo.setOrderTakingNo("1");
//        list.add(processedOrderInfo);
//        list.add(processedOrderInfo);
//        list.add(processedOrderInfo);
        return list;
    }

    private List<ProcessedOrderInfo> setValidateData(List<OrderBean> beanList) {
        List<ProcessedOrderInfo> list = new ArrayList<>();
        for (int i = 0; i < beanList.size(); i++) {
            OrderBean bean = beanList.get(i);
            ProcessedOrderInfo processedOrderInfo = new ProcessedOrderInfo();
            processedOrderInfo.setDeliveryStatus(getContext().getResources().getString(R.string.ui_processed_fast_delivery));
            processedOrderInfo.setLastComment(getContext().getResources().getString(R.string.ui_processed_last_comment));
            processedOrderInfo.setUserName(bean.getOrderUserName());
            processedOrderInfo.setUserAddress(bean.getOrderAddressName());
            processedOrderInfo.setPay(bean.getOrderCost());
            processedOrderInfo.setOrderNo(bean.getOrderId());
            processedOrderInfo.setOrderTime(bean.getOrderTime());
            List<OrderMenu> menuList = bean.getMenuList();
            processedOrderInfo.setOrderProductName(menuList.get(0).getName());
            processedOrderInfo.setOrderTakingNo(i + 1 + "");
            list.add(processedOrderInfo);
        }
        return list;
    }

    @Override
    public void onResume() {
        super.onResume();
        pullListView.setRefreshing();
        activateTimerSchedule();
    }

    @Override
    public void onPause() {
        super.onPause();
        timer.cancel();
        timer = null;
    }

    private void initView() {
        pullListView = findViewById(R.id.pullListView);
        listView = pullListView.getRefreshableView();
        pullListView.setOnRefreshListener(this);
        pullListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        header_view = View.inflate(getActivity(), R.layout.fragment_prcocessed_new_header_view, null);

        btn_printer_setting = header_view.findViewById(R.id.btn_processed_print_working);
        btn_printer_setting.setChecked(false);
        listView.addHeaderView(header_view);

        fragmentProcessedNewAdapter = new FragmentProcessedNewAdapter(getContext());
        pullListView.setAdapter(fragmentProcessedNewAdapter);
        pullListView.setOnItemClickListener(fragmentProcessedNewAdapter);
        fragmentProcessedNewAdapter.setData(setValidateData());
        if (PrintUtil.validatePrinter()) {
            orderManage.readAllOrderAsync(mOrderCallback);
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        new GetDataTask().execute();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        new GetDataTask().execute();
    }

    /**
     * Switch Button Changed event
     *
     * @param view
     * @param isChecked
     */
    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
        switch (view.getId()) {
            case R.id.btn_processed_print_working:
                if (view.isChecked()) {
                    btn_printer_setting.setChecked(true);
                } else {
                    btn_printer_setting.setChecked(false);
                }
                break;
            default:
                break;
        }
    }

    private class GetDataTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            requestOverallOrder();
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // Call onRefreshComplete when the list has been refreshed.
            pullListView.onRefreshComplete();
        }
    }

    /**
     * 自动打印小票
     */
    private void printTicket(List<OrderBean> beanList) {
        List<TicketBean> ticketBeanList = new ArrayList<>();
        for (int i = 0; i < beanList.size(); i++) {
            TicketBean bean = new TicketBean();
            bean.setAddrName(beanList.get(i).getOrderAddressName());
            bean.setCost(beanList.get(i).getOrderCost());
            bean.setMenu(beanList.get(i).getMenuList());
            bean.setOrderId(beanList.get(i).getOrderId());
            bean.setTel(beanList.get(i).getOrderUserId());
            bean.setTime(beanList.get(i).getOrderTime());
            ticketBeanList.add(bean);
        }
        if (PrintUtil.printTicket(ticketBeanList) < 0) {
            ToastUtils.showShort(getContext(), getString(R.string.process_connect_printer));
        }
    }

    private void requestOverallOrder() {
        if (!PrintUtil.validatePrinter()) {
            handler.sendEmptyMessage(MSG_REFRESH_TOAST);
            return;
        }
        String url = HttpConstant.readAllOrder(null) + "?SHOP_ID=15651723391";
        final Request request = new Request.Builder().url(url).build();
        if (okHttpClient != null) {
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Slog.e("onFailure: " + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String body = response.body().string();
                    String headers = response.headers().toString();
                    parseOrderString(body);
                    Slog.i("onResponse: " + body);
                }
            });
        }
    }

    public void initSoundPool() {
        sp = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
        hm = new HashMap<Integer, Integer>();
        hm.put(1, sp.load(getContext(), R.raw.base_auto_accept_ringtone, 1));
    }

    public void playSound(int sound, int loop) {
        AudioManager am = (AudioManager) getContext()
                .getSystemService(Context.AUDIO_SERVICE);
        float streamVolumeCurrent = am
                .getStreamVolume(AudioManager.STREAM_MUSIC);
        float streamVolumeMax = am
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float volume = streamVolumeCurrent / streamVolumeMax;
        currStreamId = sp.play(hm.get(sound), volume, volume, 1, loop, 1.0f);
    }

    private void parseOrderString(String body) {
        List<OrderBean> orderList = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(body);
            /* parse product class bean from json object */
            if (jsonObject.optString("status").equals("success")) {
                String classValues = jsonObject.optString("orderContent");
                Object object = new JSONTokener(classValues).nextValue();
                if (object instanceof JSONObject) {
                    OrderBean bean = new OrderBean();
                    bean.setOrderId(((JSONObject) object).optString("orderId"));
                    bean.setOrderUserId(((JSONObject) object).optString("tel"));
                    bean.setOrderTime(((JSONObject) object).optString("order_time"));
                    bean.setOrderCost(((JSONObject) object).optString("cost"));
                    bean.setOrderAddressName(((JSONObject) object).optString("addr_name"));
                    bean.setOrderUserName(((JSONObject) object).optString("user_name"));
                    bean.setOrderStatusId(((JSONObject) object).optString("order_status"));

                    String menu = ((JSONObject) object).optString("menu");
                    Object menuObj = new JSONTokener(menu).nextValue();
                    List<OrderMenu> list = new ArrayList<>();
                    if (menuObj instanceof JSONObject) {
                        OrderMenu orderMenu = new OrderMenu();
                        orderMenu.setName(((JSONObject) menuObj).optString("name"));
                        orderMenu.setPrice(((JSONObject) menuObj).optString("price"));
                        orderMenu.setNumb(((JSONObject) menuObj).optString("numb"));
                        list.add(orderMenu);
                    } else if (menuObj instanceof JSONArray) {
                        JSONArray jsonArray = (JSONArray) menuObj;
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject obj = jsonArray.getJSONObject(i);
                            OrderMenu orderMenu = new OrderMenu();
                            orderMenu.setName(obj.optString("name"));
                            orderMenu.setPrice(obj.optString("price"));
                            orderMenu.setNumb(obj.optString("numb"));
                            list.add(orderMenu);
                        }
                    }
                    bean.setMenuList(list);
                    orderList.add(bean);
                } else if (object instanceof JSONArray) {
                    JSONArray jsonArray = (JSONArray) object;
                    for (int m = 0; m < jsonArray.length(); m++) {
                        JSONObject details = jsonArray.getJSONObject(m);
                        OrderBean bean = new OrderBean();
                        bean.setOrderId(details.optString("orderId"));
                        bean.setOrderUserId(details.optString("tel"));
                        bean.setOrderTime(details.optString("order_time"));
                        bean.setOrderCost(details.optString("cost"));
                        bean.setOrderAddressName(details.optString("addr_name"));
                        bean.setOrderUserName(details.optString("user_name"));
                        bean.setOrderStatusId(details.optString("order_status"));

                        String menu = details.optString("menu");
                        Object menuObj = new JSONTokener(menu).nextValue();
                        List<OrderMenu> list = new ArrayList<>();
                        if (menuObj instanceof JSONObject) {
                            OrderMenu orderMenu = new OrderMenu();
                            orderMenu.setName(((JSONObject) menuObj).optString("name"));
                            orderMenu.setPrice(((JSONObject) menuObj).optString("price"));
                            orderMenu.setNumb(((JSONObject) menuObj).optString("numb"));
                            list.add(orderMenu);
                        } else if (menuObj instanceof JSONArray) {
                            JSONArray menuArray = (JSONArray) menuObj;
                            for (int i = 0; i < menuArray.length(); i++) {
                                JSONObject obj = menuArray.getJSONObject(i);
                                OrderMenu orderMenu = new OrderMenu();
                                orderMenu.setName(obj.optString("name"));
                                orderMenu.setPrice(obj.optString("price"));
                                orderMenu.setNumb(obj.optString("numb"));
                                list.add(orderMenu);
                            }
                        }
                        bean.setMenuList(list);
                        orderList.add(bean);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        handler.sendMessage(Message.obtain(handler, MSG_FRESH_ORDER_UI, orderList));
    }

    private void activateTimerSchedule() {
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(MSG_TIMER_CLOCK);
            }
        }, TIMER_CLOCK);
    }
}
